package com.yoshino.leetcode.interview150.binaryTree.search;

class Solution {
    int min = Integer.MAX_VALUE;
    // 前一个节点
    int left = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        // 对于二叉搜索树，中序遍历的排序是升序的
        if (root == null) {
            return 0;
        }
        getMinimumDifference(root.left);
        min = Math.min(Math.abs(left - root.val), min);
        left = root.val;
        getMinimumDifference(root.right);
        return min;
    }

    int k;
    int res;
    public int kthSmallest(TreeNode root, int k) {
        // 二叉搜索树，中序遍历是升序的
        this.k = k;
        kthSmallest(root);
        return res;
    }

    private void kthSmallest(TreeNode root) {
        if (root == null) {
            return;
        }
        kthSmallest(root.left);
        k--;
        if (k == 0) {
            res = root.val;
        }
        kthSmallest(root.right);
    }

    long pre = Long.MIN_VALUE;
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean l = isValidBST(root.left);
        if (root.val <= pre) {
            return false;
        }
        pre = root.val;
        boolean r = isValidBST(root.right);
        return l && r;
    }

}